package com.hzpd.hainan.module.news.activity;

import android.content.Intent;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.hzpd.hainan.R;
import com.hzpd.hainan.api.InterfaceJsonfile;
import com.hzpd.hainan.app.ToolBarActivity;
import com.hzpd.hainan.custorm.ListViewInScrollView;
import com.hzpd.hainan.model.base.BaseEntity;
import com.hzpd.hainan.model.news.CommenEntity;
import com.hzpd.hainan.model.news.CommentBean;
import com.hzpd.hainan.model.news.IsCollectionEntity;
import com.hzpd.hainan.model.news.NewsBean;
import com.hzpd.hainan.model.news.NewsListEntity;
import com.hzpd.hainan.model.news.SubJectTypeBean;
import com.hzpd.hainan.model.news.SubjectItemColumnsBean;
import com.hzpd.hainan.model.news.SubjectTypeEntity;
import com.hzpd.hainan.module.news.adapter.CommentAdapter;
import com.hzpd.hainan.module.news.adapter.ZhuantiDetailListAdapter;
import com.hzpd.hainan.module.news.dialog.InputPop;
import com.hzpd.hainan.net.Factory;
import com.hzpd.hainan.utils.AAnim;
import com.hzpd.hainan.utils.LogUtils;
import com.hzpd.hainan.utils.PageCtrl;
import com.hzpd.hainan.utils.ParamUtils;
import com.hzpd.hainan.utils.StringUtils;
import com.hzpd.hainan.utils.TUtils;
import com.hzpd.hainan.wxapi.SharedUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnItemClick;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by 猪猪侠 on 2017/7/7.
 */

public class NewsZhuanTiActivity extends ToolBarActivity {
    @BindView(R.id.zhuanti_item_sv)
     PullToRefreshScrollView zhuanti_item_sv;
    @BindView(R.id.zhuanti_topview_myroot)
     LinearLayout zhuanti_topview_myroot;
    @BindView(R.id.zhuanti_header_iv)
     ImageView zhuanti_header_iv;
    @BindView(R.id.zhuanti_head_iv)
     ImageView zhuanti_head_iv;
    @BindView(R.id.et_pinglun_id)
     EditText et_pinglun_id;
    @BindView(R.id.zhuanti_item_listview)
    ListViewInScrollView mXListView;
    @BindView(R.id.newdetail_comm_listview)
     ListViewInScrollView newdetail_comm_listview;
    @BindView(R.id.zhuanti_item_iv)
     ImageView zhuanti_item_iv;
    @BindView(R.id.zhuanti_tv_content)
     TextView zhuanti_tv_content;
    @BindView(R.id.comments_news_ll)
     LinearLayout comments_news_ll;
    @BindView(R.id.rl_newdetail_collection)
     RelativeLayout rl_newdetail_collection;// 收藏
    @BindView(R.id.xf_newshtmldetail_iv_collection)
     ImageView xf_newshtmldetail_iv_collection;

    private CommentAdapter commAdapter;
    private ZhuantiDetailListAdapter adapter;
    private String from;//newsitem subject
    private boolean mFlagRefresh;
    private int page = 1;
    private static final int pageSize = 15;//
    int i = 0;
    private NewsBean nb=null;//专题id
    private String nid = "";
    private InputPop inputPop;
    private List<SubjectItemColumnsBean> columnList;
//    private static final String BASEURL = InterfaceJsonfile.PATH_ROOT + "/index.php?s=/Public/newsview/nid/";
    @Override
    public String initToolBarTitle() {
        return null;
    }

    @Override
    public int setMyContentView() {
        return R.layout.special_detail_layout;
    }

    @Override
    public void initView() {
        mXListView.postDelayed(new Runnable() {
            @Override
            public void run() {
                zhuanti_item_sv.setRefreshing(true);
            }
        }, 200);
    }

    @Override
    public void initData() {
        init();
    }
    private void init(){
        Intent intent= getIntent();
        from=intent.getStringExtra("from");
        LogUtils.i("from-->"+from);
        if("newsitem".equals(from)){
            nb=(NewsBean) intent.getSerializableExtra("newbean");
            LogUtils.i("nid--->"+ nb.getNid());
        }else if("subject".equals(from)){
            nb=(NewsBean) intent.getSerializableExtra("nb");
        }else {
            nb=(NewsBean) intent.getSerializableExtra("newbean");
        }
        if(null==nb){
            return;
        }

        List<String> imgs=nb.getImgs();
        String img="";
        if(null!=imgs&&imgs.size()>0){
            img=imgs.get(0);
        }
        commAdapter  = new CommentAdapter(activity,0);
        newdetail_comm_listview.setAdapter(commAdapter);
        mXListView.setEmptyView(zhuanti_item_iv);
        zhuanti_item_sv.setMode(PullToRefreshBase.Mode.DISABLED);
        adapter = new ZhuantiDetailListAdapter(activity);
        mXListView.setAdapter(adapter);
        getColumns();
        isCollection();
        //总共多少篇
//        getCounts(nb.getNid());
    }
    @OnClick({R.id.rl_newdetail_collection,R.id.newdetail_share,R.id.zhuanti_header_iv,R.id.et_pinglun_id,R.id.news_detail_bak})
    void goback(View v)
    {
        switch (v.getId()){
            case R.id.newdetail_share: {
                LogUtils.i("click share");
                String imgurl = null;
                if (null != nb.getImgs() && nb.getImgs().size() > 0) {
                    imgurl = nb.getImgs().get(0);
                }
                nid=nb.getNid();
                SharedUtil.showShares(true, null, "今日海北", InterfaceJsonfile.BASEURL +nid , imgurl, activity);
            }
            break;
            case R.id.rl_newdetail_collection: {// 收藏
                if (spu.getUser()!=null){
                    addCollection();
                }else{
                    PageCtrl.start2LoginActivity(activity);
                }

            }
            break;
            case R.id.news_detail_bak:
                finish();
                break;
            case R.id.et_pinglun_id:
                if (spu.getUser()!=null){
                    popCommentActivity(null);
                }else{
                    PageCtrl.start2LoginActivity(activity);
                }
                break;
            case R.id.zhuanti_header_iv:
                if (!StringUtils.isEmpty(nid)){
                    Intent mIntent = new Intent();
                    NewsBean newsBean = new NewsBean();
                    newsBean.setNid(nid);
                    mIntent.putExtra("newbean", newsBean);
                    mIntent.putExtra("from", "newsitem");
                    mIntent.setClass(this,NewsHtmlDetailActivity.class);
                    startActivity(mIntent);
                    AAnim.ActivityStartAnimation(this);
                }else{
                    TUtils.toast("获取数据失败");
                }


                break;
        }
    }
    //专题栏目列表
    public void getColumns(){
        Map<String,String> map = new HashMap<>();
        map.put("sid",nb.getNid());
        Factory.provideHttpService().newsSubjectColumn(map)
                .subscribeOn(Schedulers.io())
                .filter(new Func1<SubjectTypeEntity, Boolean>() {
                    @Override
                    public Boolean call(SubjectTypeEntity entity) {
                        if ("200".equals(entity.code)){
                            return true;
                        }else{
                            return false;
                        }
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<SubjectTypeEntity>() {
                    @Override
                    public void call(SubjectTypeEntity entity) {
                        zhuanti_item_sv.onRefreshComplete();
                        if ("200".equals(entity.code)){
                            nid=entity.data.getMainid();
                            getCommentList();
                            String imgmain = entity.data.getMainimg();
                            String imgnews = entity.data.getPhoto();
                            //photo 是顶部细图
                            //main 是主图
//                            Glide.with(activity).load(imgnews).crossFade().placeholder(R.drawable.zhuangti_head).into(zhuanti_head_iv);
                            Glide.with(activity).load(imgnews).crossFade().placeholder(R.drawable.default_bg).into(zhuanti_header_iv);
//                            zhuanti_head_iv.setVisibility(View.VISIBLE);
                            setImageLayoutParams(zhuanti_header_iv);//设置图片的高度为宽度的0.45
                            zhuanti_header_iv.setVisibility(View.VISIBLE);
                            columnList = entity.data.getColumns();
//                            String desc = entity.data.getDescription();
//                            if (StringUtils.isEmpty(desc)){
//                                zhuanti_tv_content.setVisibility(View.GONE);
//                            }else{
//                                zhuanti_tv_content.setVisibility(View.VISIBLE);
//                                zhuanti_tv_content.setText(desc);
//                            }
                            if(null!=columnList&&columnList.size()>0){
                                for (int i = 0;i<columnList.size();i++){
                                    getServerList(columnList.get(i));
                                    try {
                                        Thread.currentThread().sleep(300);
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        zhuanti_item_sv.onRefreshComplete();
                        LogUtils.i("getColumns-->faild-->"+throwable);
                    }
                });


    }
    //TODO
    private void getCommentList(){
        Map<String,String> map = new HashMap<>();
        map.put("nid",nid);
        map.put("type","1");
        map.put("Page",page+"");
        map.put("PageSize","15");
        map.put("siteid",InterfaceJsonfile.SITEID);

        Factory.provideHttpService()
                .newsCommentList(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<CommenEntity, Boolean>() {
                    @Override
                    public Boolean call(CommenEntity entity) {
                        LogUtils.i("200-->" + entity.code);
                        if ("200".equals(entity.code)) {
                            return true;
                        }
                        return false;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<CommenEntity>() {
                    @Override
                    public void call(CommenEntity entity) {
                        if ("200".equals(entity.code)){
                            comments_news_ll.setVisibility(View.VISIBLE);
                            newdetail_comm_listview.setVisibility(View.VISIBLE);
                            commAdapter.appendData(entity.data, mFlagRefresh);
                            commAdapter.notifyDataSetChanged();
                            //------+
                            //----
                            if (entity.data.size() < 15) {
                                zhuanti_item_sv.setMode(PullToRefreshBase.Mode.DISABLED);
                            } else {
                                zhuanti_item_sv.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
                            }

                        }else{
                            zhuanti_item_sv.setMode(PullToRefreshBase.Mode.DISABLED);
                            TUtils.toast(entity.msg);
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        zhuanti_item_sv.onRefreshComplete();
                    }
                });
    }
    //TODO
    private void getServerList(final SubjectItemColumnsBean sicb){
        Map<String,String> map = new HashMap<>();
        map.put("cid", sicb.getCid());
        map.put("Page", page+"");
        map.put("PageSize",pageSize+"");
        Factory.provideHttpService().newsSubjectNewsList(map)
                .subscribeOn(Schedulers.io())
                .filter(new Func1<NewsListEntity, Boolean>() {
                    @Override
                    public Boolean call(NewsListEntity entity) {
                        if ("200".equals(entity.code)){
                            return true;
                        }else{
                            return false;
                        }
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<NewsListEntity>() {
                    @Override
                    public void call(NewsListEntity entity) {
                        List<NewsBean> list = entity.data;
                        adapter.appendData(sicb,list,mFlagRefresh);
                        adapter.notifyDataSetChanged();
//								zhuanti_item_sv.setMode(Mode.BOTH);
                        zhuanti_item_sv.setMode(PullToRefreshBase.Mode.DISABLED);


                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {

                    }
                });
    }
    //是否收藏
    private void isCollection() {
        Map<String, String> map = new HashMap<>();
        if (spu.getUser()==null){
            return;
        }
        map.put("typeid", nb.getNid());
        map.put("uid", spu.getUser().getUid());
        map.put("type", "3");
        Factory.provideHttpService()
                .newsIsCollection(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<IsCollectionEntity, Boolean>() {
                    @Override
                    public Boolean call(IsCollectionEntity entity) {
                        LogUtils.i("200-->" + entity.code);
                        if ("200".equals(entity.code)) {
                            LogUtils.i("200-->成功");
                            return true;
                        }
                        LogUtils.i("200失败");
                        return false;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<IsCollectionEntity>() {
                    @Override
                    public void call(IsCollectionEntity entity) {
                        if ("200".equals(entity.code)){
                            if ("1".equals(entity.data.getStatus())){
                                xf_newshtmldetail_iv_collection.setImageResource(R.drawable.zqzx_collection);
                            }
                        }else{
                            TUtils.toast(entity.msg);
                        }
//                        setData();
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                    }
                });
    }

    private void addCollection(){
        if (null == spu.getUser()) {
            TUtils.toast("请登录");
            return;
        }
//        xf_newshtmldetail_iv_collection.setImageResource(R.drawable.zqzx_nd_collection);

//        LogUtils.i("Type-->" + nb.getType() + "  Fid-->" + nb.getNid());
        showDialog();
        Map<String,String> map = new HashMap<>();
        map.put("typeid", nb.getNid());
        map.put("uid",spu.getUser().getUid());
        map.put("type", "1");
        map.put("siteid", InterfaceJsonfile.SITEID);
        Factory.provideHttpService()
                .newsAddCollection(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<IsCollectionEntity, Boolean>() {
                    @Override
                    public Boolean call(IsCollectionEntity entity) {
                        LogUtils.i("200-->" + entity.code);
                        if ("200".equals(entity.code)) {
                            return true;
                        }
                        return false;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<IsCollectionEntity>() {
                    @Override
                    public void call(IsCollectionEntity entity) {
                        disMissDialog();
                        if ("200".equals(entity.code)){
                            if ("1".equals(entity.data.getStatus())){
                                TUtils.toast("收藏成功");
                                xf_newshtmldetail_iv_collection.setImageResource(R.drawable.zqzx_collection);
                            } else {
                                xf_newshtmldetail_iv_collection.setImageResource(R.drawable.zqzx_nd_collection);
                                TUtils.toast("收藏取消");
                            }
                        }else{
                            TUtils.toast(entity.msg);
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LogUtils.i("addCollection-->收藏失败");
                        disMissDialog();
                    }
                });
    }
    //评论新闻
private void popCommentActivity(final CommentBean commentBean){
    if (null == spu.getUser()) {
        TUtils.toast("请登录");
        return;
    }
    if (null == nb) {
        return;
    }
    if (!"0".equals(nb.getComflag())) {
        if (inputPop == null){
            inputPop = new InputPop(activity, new InputPop.InputListener() {
                @Override
                public void inputstr(String string) {
                    if (commentBean != null) {
                        sendComment(string);
                    }else {
                        sendComment(string);
                    }
                }
            });
        }
        inputPop.setFocusable(true);
        inputPop.showAtLocation(findViewById(R.id.root_ll), Gravity.BOTTOM,0,0);
    } else {
        TUtils.toast("该条专题不可评论");
    }
}
    // 发表评论
    private void sendComment(String content) {
        showDialog();
        Map<String, String> map = new HashMap<>();
        map.put("nid", nb.getNid());
        map.put("uid", spu.getUser().getUid());
        map.put("type", "1");
        map.put("content", content);
        map.put("siteid", InterfaceJsonfile.SITEID);
        Factory.provideHttpService()
                .newsComment(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<BaseEntity, Boolean>() {
                    @Override
                    public Boolean call(BaseEntity entity) {
                        LogUtils.i("200-->" + entity.code);
                        if ("200".equals(entity.code)) {
                            LogUtils.i("200-->成功");
                            return true;
                        }
                        LogUtils.i("200失败");
                        return false;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<BaseEntity>() {
                    @Override
                    public void call(BaseEntity entity) {
                        disMissDialog();
                        if ("200".equals(entity.code)){
                            TUtils.toast("评论成功");
                            et_pinglun_id.setText("");
                        }else{
                            TUtils.toast(entity.msg);
                        }
//                        setData();
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        TUtils.toast("评论失败");
                        disMissDialog();
                    }
                });
    }
    @OnItemClick(R.id.zhuanti_item_listview)
    public void listviewonItemClick(AdapterView<?> parent, View view,int position, long id){
        NewsBean nb=null;
        int type=adapter.getItemViewType(position);
        if(0==type){
            return;
        }else{
            nb= (NewsBean) adapter.getItem(position);
        }
        if(null==nb){
            LogUtils.i("nb null");
            return;
        }
        String detailId = nb.getNid();

        LogUtils.i("detailId-->"+detailId);
        Intent in = new Intent(this, NewsHtmlDetailActivity.class);
        in.putExtra("newbean", nb);
        in.putExtra("from", "news");

        startActivity(in);
        AAnim.ActivityStartAnimation(this);
    }
    public void setImageLayoutParams(ImageView imageView){
        ViewGroup.LayoutParams params;
        params= (ViewGroup.LayoutParams) imageView.getLayoutParams();
        int width=activity.getWindowManager().getDefaultDisplay().getWidth();
        params.width=width;
        params.height= (int) (width*0.45);
        imageView.setLayoutParams(params);
    }
}
